//
//  WeatherController.m
//  quickDoctor
//
//  Created by zhaowei on 17/3/11.
//  Copyright © 2017年 SWS. All rights reserved.
//

#import "WeatherController.h"
#import "LocationTableController.h"
#import "CityTableViewController.h"

@interface WeatherController ()<NSCoding>

@property (nonatomic,strong)UIButton *locationButton;
@property (nonatomic,strong)  NSDictionary* dict;

//imageView
@property (nonatomic,weak)UIImageView *imageView;
//weaLabel
@property (nonatomic,weak)UILabel *weaLabel;

@property (nonatomic,weak)UILabel *temperatureLabel;

@property (nonatomic,weak)UILabel *duLabel;

@property (nonatomic,weak)UILabel *dateLabel;

@property (nonatomic,weak)UILabel *concreteDateLabel;



@end

@implementation WeatherController {
     NSDictionary *_weatherDict;
}


- (void)viewDidLoad {
     [super viewDidLoad];
    
     [self setupUI];
     [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(locationPop:) name:@"location" object:nil];
    
//    [self loadData];

    //读取数据
    [self readValue];
    [self setValue];
    [self performSelectorInBackground:@selector(loadData) withObject:nil];
    
}

#pragma mark
#pragma mark -读取数据
- (void)readValue{
    
    //路径
    NSString *fileName = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).lastObject stringByAppendingPathComponent:@"weather.plist"];
    
    NSDictionary *weatherDict = [NSKeyedUnarchiver unarchiveObjectWithFile:fileName];
    _weatherDict = weatherDict;
}


- (void)locationPop:(NSNotification *)notification {
    //取出城市名字
    NSString *cityName = notification.userInfo[@"cityName"];
    _locaName = cityName;
    
//    [self loadData];
    [self performSelectorInBackground:@selector(loadData) withObject:nil];
}

- (void)loadData {
    if(_locaName == nil) {
        [self GETWithLocation:@"上海"];
    }else {
        [self GETWithLocation:_locaName];
    }
}
/// 请求数据
- (void)GETWithLocation:(NSString *)str {
    
    NSString *urlStr = @"http://api.map.baidu.com/telematics/v3/weather";
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    parameters[@"location"] = str;
    parameters[@"output"] = @"json";
    parameters[@"ak"] = @"17IvzuqmKrK1cGwNL6VQebF9";
    
    [[NETWorkTool sharedTool] GETWithUrlStr:urlStr parameters:parameters success:^(NSDictionary *responceObject) {
        // 获取字典数组
        NSArray *resultArr = responceObject[@"results"];
        //取出里面对应的天气数组
        NSDictionary *dict = resultArr.lastObject;
        //        NSDictionary *dict = dictArr[0];
        NSArray *weatherArr = dict[@"weather_data"];
        NSDictionary *weatherDict = weatherArr.firstObject;
        _weatherDict = weatherDict;
        
        //写入数据
        [self saveValue];
        

        [self performSelectorOnMainThread:@selector(setValue) withObject:nil waitUntilDone:NO];

    } failure:^(NSError *error) {
        NSLog(@"%@",error);

    }];
}
#pragma mark
#pragma mark -写入数据
- (void)saveValue {
    //路径
    NSString *fileName = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).lastObject stringByAppendingPathComponent:@"weather.plist"];
    [NSKeyedArchiver archiveRootObject:_weatherDict toFile:fileName];
}

#pragma mark
#pragma mark -归档
- (void)encodeWithCoder:(NSCoder *)aCoder {
    [aCoder encodeObject:_weatherDict forKey:@"weather"];
}
#pragma mark
#pragma mark -解档
- (instancetype)initWithCoder:(NSCoder *)aDecoder {
    if(self = [super init]) {
        
        _weatherDict = [aDecoder decodeObjectForKey:@"weather"];
    }
    return self;
}



/*
 请求地址：http://api.map.baidu.com/telematics/v3/weather
 请求参数：（city填什么，大家都懂的！）{@"location":city,@"output":@"json",@"ak":@"17IvzuqmKrK1cGwNL6VQebF9"};
 
 */

/*
 {
 date = "\U5468\U56db 03\U670809\U65e5 (\U5b9e\U65f6\Uff1a16\U2103)";
 dayPictureUrl = "http://api.map.baidu.com/images/weather/day/qing.png";
 nightPictureUrl = "http://api.map.baidu.com/images/weather/night/duoyun.png";
 temperature = "17 ~ 8\U2103";
 weather = "\U6674\U8f6c\U591a\U4e91";
 wind = "\U897f\U5357\U98ce\U5fae\U98ce";
 }
 
 */
//53 193 189

- (void)setupUI{
    //添加imageView
    UIImageView *imageView = [[UIImageView alloc] init];
    _imageView = imageView;
       [self.view addSubview:imageView];
    
    //添加天气状况label
    UILabel *weaLabel = [[UILabel alloc] init];
    _weaLabel = weaLabel;
       weaLabel.font = [UIFont systemFontOfSize:13];
    weaLabel.textColor = RGBACOLOR(53, 193, 189, 1);
    [self.view addSubview:weaLabel];
    
    //添加地点button
    UIButton *locationButton = [[UIButton alloc] init];
    _locationButton = locationButton;
    
    
    locationButton.titleLabel.font = [UIFont systemFontOfSize:15];
    [locationButton setTitleColor:RGBACOLOR(53, 193, 189, 1) forState:UIControlStateNormal];
    [locationButton addTarget:self  action:@selector(notification) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:locationButton];
    
    //添加点击事件
    [locationButton addTarget:self action:@selector(clickChose) forControlEvents:UIControlEventTouchUpInside];
    
    //添加细线
    UIImageView *lineImageView = [[UIImageView alloc] init];
    lineImageView.image = [UIImage imageNamed:@"fengexian"];
    [self.view addSubview:lineImageView];
    
    //添加温度label
    UILabel *temperatureLabel = [[UILabel alloc] init];
    _temperatureLabel = temperatureLabel;
    
    temperatureLabel.textColor = RGBACOLOR(53, 193, 189, 1);
    temperatureLabel.font = [UIFont systemFontOfSize:12];
    _temperatureLabel.text = @"温度:";
    [temperatureLabel sizeToFit];
    [self.view addSubview:temperatureLabel];
    
    //添加度数label
    UILabel *duLabel = [[UILabel alloc] init];
    _duLabel = duLabel;
   
    [duLabel sizeToFit];
    duLabel.textColor = RGBACOLOR(53, 193, 189, 1);
    [self.view addSubview:duLabel];
    
    //添加日期label
    UILabel *dateLabel = [[UILabel alloc] init];
    dateLabel.text = @"日期:";
    _dateLabel = dateLabel;
   
    dateLabel.textColor = RGBACOLOR(53, 193, 189, 1);
    dateLabel.font = [UIFont systemFontOfSize:12];
    [self.view addSubview:dateLabel];
    
    //添加具体时间label
    UILabel *concreteDateLabel = [[UILabel alloc] init];
    _concreteDateLabel = concreteDateLabel;
    [concreteDateLabel sizeToFit];
       concreteDateLabel.font = [UIFont systemFontOfSize:11];
    concreteDateLabel.textColor = RGBACOLOR(53, 193, 189, 1);
    [self.view addSubview:concreteDateLabel];
    
    
    //约束
    //imageView
    [imageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.offset(0);
        make.width.mas_equalTo(40);
        make.leading.offset(10);
        make.height.mas_equalTo(40);
    }];
    //天气label
    [weaLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.equalTo(imageView.mas_trailing).offset(5);
        make.centerY.equalTo(self.view);
        make.width.mas_equalTo(80);
    }];
    //细线
    [lineImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(60);
        make.centerX.centerY.equalTo(self.view);
        make.width.mas_equalTo(1);
    }];
    //地点
    [locationButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.offset(0);
        make.trailing.equalTo(lineImageView.mas_leading).offset(-10);
        make.width.mas_equalTo(40);
    }];
    //温度label
    [temperatureLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.equalTo(lineImageView.mas_trailing).offset(30);
        make.top.offset(8);
        make.width.mas_equalTo(40);
    }];
    //具体温度
    [duLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.equalTo(temperatureLabel.mas_trailing).offset(3);
        make.centerY.equalTo(temperatureLabel);
        
    }];
    //日期
    [dateLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(temperatureLabel.mas_bottom).offset(5);
        make.leading.equalTo(lineImageView.mas_trailing).offset(10);
        make.width.mas_equalTo(30);
        
    }];
    //具体时间
    [concreteDateLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(duLabel.mas_bottom).offset(10);
        make.centerY.equalTo(dateLabel);
        make.leading.equalTo(dateLabel.mas_trailing).offset(5);
        
    }];
    
    
}
#pragma mark
#pragma mark -赋值
- (void)setValue {
    //imageView
    NSString *urlStr = _weatherDict[@"dayPictureUrl"];
    NSURL *url = [NSURL URLWithString:urlStr];
    NSData *data = [NSData dataWithContentsOfURL:url];
    _imageView.image= [UIImage imageWithData:data];
    //weaLabel
    NSString *urlStr1 = _weatherDict[@"weather"];
    _weaLabel.text = urlStr1;
    
    if(_locaName ==nil) {
        [_locationButton setTitle:@"上海" forState:UIControlStateNormal];
    }else {
        [_locationButton setTitle:_locaName forState:UIControlStateNormal];
    }

    
    
    NSString *duUrlStr = _weatherDict[@"temperature"];
    _duLabel.text = duUrlStr;
    
    
    NSString *dateUrlStr = _weatherDict[@"date"];
    _concreteDateLabel.text = dateUrlStr;

    

}
/// 发送通知
- (void)notification {
    
    [[NSNotificationCenter defaultCenter] postNotificationName:@"push" object:nil];
    
    
}

/// 点击跳转
- (void)clickChose {
    
    //创建tableController
    LocationTableController *locController = [[LocationTableController alloc] init];
    
    [self.navigationController pushViewController:locController animated:YES];
    
 
}



@end
